/*
 * Copyright 2010    Sylvere RICHARD
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.infotrafficlux.server.controller;

import java.util.Collection;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.google.infotrafficlux.server.bean.Place;
import com.google.infotrafficlux.server.dao.PlaceDao;
import com.google.infotrafficlux.server.validator.NewPlaceValidator;

@Controller
@RequestMapping("/place")
public class PlaceController {

	private static final Logger logger = Logger
			.getLogger(PlaceController.class);

	private PlaceDao dao;

	public PlaceDao getDao() {
		return dao;
	}

	@Autowired
	public void setDao(PlaceDao dao) {
		this.dao = dao;
	}

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.setValidator(new NewPlaceValidator());
	}

	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public Collection<Place> getAllPlaces() {
		Collection<Place> places = dao.getAllPlaces(1, 100);
		
		return places;
	}

	@RequestMapping("/{placeid}")
	@ResponseBody
	public Place getPlace(@PathVariable("placeid") Long placeid) {
		Place place = dao.getPlace(placeid);
		
		return place;
	}

	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public String addPlace(@RequestBody /*@Valid*/ NewPlace p/*, BindingResult result, Model model*/) {
		
		logger.debug("adding " + p);
		//if (result.hasErrors()) {
			//return Long.valueOf(-1);
			//return "-1";
		//}

		return dao.insertOrUpdate(p.asPlace()).toString();
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	public void deletePlace(@PathVariable Long id) {
		dao.delete(id);
	}

}
